package com.sy.service.settings.impl;

import com.sy.bean.settings.Dictionary;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.crud.IService;
import com.sy.common.exception.BusinessException;
import com.sy.mapper.settings.DictionaryMapper;
import com.sy.service.settings.DictionaryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@Service
public class DictionaryServiceImpl extends BaseServiceImpl<Dictionary, DictionaryMapper> implements DictionaryService {
    String currentMaxCode; //当前最大编码

    @Override
    public List<Dictionary> queryDict(String code) {
        return baseMapper.queryDict(code);
    }

    @Override
    @Transactional
    public int saveDict(Dictionary dictionary) {
        dictionary.setCode(generateCode(dictionary.getCodes()));
        String sorts=baseMapper.queryMaxSorts(dictionary.getCodes())+"";
        if (sorts!=null||sorts.equals("")){
            dictionary.setSorts(1);
        }
        int a=Integer.parseInt(sorts);
        a++;
        dictionary.setSorts(a);
        int rs= baseMapper.saveDict(dictionary);
        if (rs == 0)
            throw new BusinessException("保存字典失败");
        return 1;
    }


    @Override
    public int updateDict(Dictionary dictionary) {
        return baseMapper.updateDict(dictionary);
    }

    @Override
    public int delDict(int id) {
        return baseMapper.delDict(id);
    }

    String generateCode(String code) {
        //判断当前最大编码是否存在
        if (null == currentMaxCode) {
            //如果不存在，查询当年最大编码
            currentMaxCode = baseMapper.queryMaxCode(code);
            if (null == currentMaxCode) {
                //说明不存在，生产第一个编码
                currentMaxCode = "1000001";
            } else {
                //如果存在，新编码序号+1
                getNextCode();
            }
        } else {
            //如果存在，新编码序号+1
            getNextCode();
        }
        return currentMaxCode;
    }

    void getNextCode() {
        //1000001
        String prefix = currentMaxCode.substring(0, 4);
        String seq = currentMaxCode.substring(4);
        //转换数字001. tmp=1
        int tmp = Integer.parseInt(seq);
        tmp++;
        currentMaxCode = prefix + String.format("%03d", tmp);
    }

}
